import face_recognition,core,json,core.face_data,core.thred_pool
import core.face_data as face_data

class MatchResult:
    def __init__(self, is_match):
        self.is_match = is_match
        self.face_data = None
    def matched(self,face_data):
        self.is_match = True
        self.face_data = face_data
    def get(self):
        return self.is_match  
    
def face_match(file_stream):
    img = face_recognition.load_image_file(file_stream)
    unknown_face_encodings = face_recognition.face_encodings(img)
    return excute_match_async(unknown_face_encodings)
      

def face_train(file_stream,uuid,name):
    img = face_recognition.load_image_file(file_stream)
    face_encodings = face_recognition.face_encodings(img)
    if len(face_encodings) > 0:
        data = {
            "uuid": uuid,
            "name": name,
            "face_encoding": face_encodings[0].tolist()  # 将 NumPy 数组转换为列表
        }
        face_data.save(data)
        return True
    return False    
      

def excute_match_async(unknown_face_encoding):
   match_result = MatchResult(False)
   if len(unknown_face_encoding) == 0:
        return match_result
   # 提交多批任务
   futures = []
   for index in range(core.face_data.THREAD_NUMS): 
        face_datas = face_data.get_face_dataList(index)
        batch_futures = core.thred_pool.get().submit(excute_match,unknown_face_encoding,face_datas,match_result) 
        futures.append(batch_futures)
    
   # 等待所有任务完成
   for future in futures:
        future.result()
   # 获取匹配结果
   return match_result 

def excute_match(unknown_face_encoding,face_datas,match_result:MatchResult):
    for face_data in face_datas:
        if match_result.get():
            break
        face_encoding = face_data["face_encoding"]
        match_results = face_recognition.compare_faces([face_encoding], unknown_face_encoding[0],0.4)
        if match_results[0]:
            match_result.matched(face_data)
            break